package mt.demo.service.system;

import mt.demo.dao.SysFunctionDao;
import mt.demo.domain.system.SysFunctionDomain;
import mt.demo.domain.user.UserRoleDomain;
import mt.demo.service.comm.YomsException;
import mt.demo.service.user.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.testng.log4testng.Logger;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by watson on 2015/12/14.
 */
@Service
public class SysFunctionService {
    @Autowired
    private RoleService roleService;
    @Autowired
    private SysFunctionDao sysFunctionDao;
    //查找所有功能
    public List<SysFunctionDomain> getAllSysFunction(SysFunctionDomain sysFunctionDomain)throws YomsException{
        List<SysFunctionDomain> domains=sysFunctionDao.getDomainByCondition(sysFunctionDomain);
        return domains;
    }
    //为角色分配和撤销功能
    private Map<Integer, SysFunctionDomain> allDomains = null;   //系统
    /**
     * 根据角色集合获取权限列表
     *
     * @param roles
     * @return
     */
    public List<SysFunctionDomain> getRoleFunction(List<UserRoleDomain> roles) throws YomsException {

        SysFunctionDomain sysFunction = null;
        sysFunction = new SysFunctionDomain();
        //所有请求都必须加入Role_User权限
        sysFunction.setSysFuncNo("ROLE_USER");

        List<SysFunctionDomain> functions = new ArrayList<>();
        functions.add(sysFunction);

        for (UserRoleDomain role : roles) {
            //keySet().iterator()返回hash里面的全部key的集合，然后去除重复的元素
            Iterator<Integer> keys = allDomains.keySet().iterator();
            while (keys.hasNext()) {
                SysFunctionDomain domain = allDomains.get(keys.next());
                long roleFunc = role.getUserRoleFunction0();
                long funcValue = domain.getSysFuncValue();
                if ((roleFunc & funcValue) == funcValue) {
                    functions.add(domain);
                    //在日志信息里面打印出编号和名称
                    Logger.getLogger(this.getClass()).debug(String.format("functionNo=%s&functionName=%s", domain.getSysFuncNo(), domain.getSysFuncName()));
                }
            }
        }
        return functions;
    }
}
